<template>
	<view class="page">
		<uni-forms ref="formRef" :rules="rules" :modelValue="formData" label-width="70px">
			<uni-forms-item label="手机号码" name="mobile">
				<uni-easyinput type="number" v-model="formData.mobile" placeholder="请输入手机号" maxlength="11" />
			</uni-forms-item>
			<uni-forms-item label="验证码" name="verifyCode">
				<div class="flex">
					<uni-easyinput type="text" v-model="formData.verifyCode" placeholder="请输入验证码" />
					<button @click="clickGetCode" class="uni-ml-3 center" size="mini" style="line-height: 2.8;">获取验证码</button>
				</div>
			</uni-forms-item>
		</uni-forms>
		<button class="button" @click="submit">登陆</button>
	</view>
</template>

<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import request from '../../utils/request';

const formRef = ref(null);

const formData = reactive({
	mobile: '',
	verifyCode: ''
});

let lastGetCodeTimesTamp = 0;
	
const rules = {
	mobile: {
		label: '手机号',
		rules: [
			{
				required: true,
			},
			{
				pattern: "^1[3-9][0-9]\\d{4,8}$",
				errorMessage: "请输入正确的手机号码"
			}
		]
	},
	verifyCode: {
		label: '验证码',
		rules: [
			{
				required: true,
			},
		]
	}
};

// 点击获取验证码
const clickGetCode = async () => {
	const now = new Date().getTime();
	if (lastGetCodeTimesTamp == 0 || now - lastGetCodeTimesTamp <= 600000) {
		request({
			method: 'POST',
			url: '/app/member/verifycode/send',
			contentTypeIsForm: true,
			data: {
				mobile: formData.mobile,
			},
			showLoading: {}
		});
		lastGetCodeTimesTamp = new Date().getTime();
		uni.showToast({
			title: "已发送验证码",
			icon: "success"
		});
	}
};

// 点击提交
const submit = async () => {
	try {
		formRef.value!.validate();
		const { token, userId } = await request({
			url: '/app/member/mobile/login',
			method: 'POST',
			contentTypeIsForm: false,
			data: {
				...formData
			},
			showLoading: {
				title: '登陆中...'
			},
			errorToast: true
		});
		uni.showToast({
			title: '登陆成功',
			icon: "success"
		});
		// console.log("token: ", token);
		// console.log("userId: ", userId);
		uni.setStorageSync("TOKEN", token);
		uni.setStorageSync("USER_ID", userId);
		uni.navigateTo({
			url: '/pages/index/index'
		});
	} catch(e) {
		//TODO handle the exception
	}
};

onMounted(() => {
	const instance = getCurrentInstance();
	console.log("instance.proxy: ", instance.proxy);
})
</script>

<style lang="scss" scoped>
.page {
	padding: 15px;
}
</style>
